package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.lims.model.CommandSend;
import com.foreverwin.mes.lims.service.CommandSendService;
import com.foreverwin.mes.lims.service.ProducerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.CommandReviewService;
import com.foreverwin.mes.lims.model.CommandReview;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 *
 * @author Max
 * @since 2020-02-28
 */
@Controller
@RequestMapping("/commandReviews")
public class CommandReviewController {
    private final Logger logger = LoggerFactory.getLogger(CommandReviewController.class);

    @Autowired
    public CommandReviewService commandReviewService;
    @Autowired
    public CommandSendService commandSendService;
    @Autowired
    public ProducerService producerService;
    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getCommandReviewById(@PathVariable String id) {
        CommandReview result;
        try {
            result = commandReviewService.selectById(id);
        } catch (Exception e) {
            logger.error("getCommandReviewById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getCommandReviewList(CommandReview commandReview){
        List<CommandReview> result;
        try {
            result = commandReviewService.selectReviewCommand(commandReview);
        } catch (Exception e) {
            logger.error("getCommandReviewList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getCommandReviewPageList")
    public AjaxResult getCommandReviewPageList(FrontPage<CommandReview> frontPage, CommandReview commandReview){
        Page result;
        try {
            String site = CommonMethods.getSite();
            commandReview.setSite(site);
            EntityWrapper<CommandReview> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(commandReview);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("zCommandSendBo", frontPage.getGlobalQuery())
                    .or().like("resrce", frontPage.getGlobalQuery())
                    .or().like("resrceDesc", frontPage.getGlobalQuery())
                    .or().like("applyType", frontPage.getGlobalQuery())
                    .or().like("event", frontPage.getGlobalQuery())
                    .or().like("message", frontPage.getGlobalQuery())
                    .or().like("submitter", frontPage.getGlobalQuery())
                    .or().like("reviewStatus", frontPage.getGlobalQuery())
                    .or().like("creator", frontPage.getGlobalQuery())
                    .or().like("updater", frontPage.getGlobalQuery())
        ;
            }
            result = commandReviewService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getCommandReviewPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存审核结果
     * @param commandReview  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult commandReviewSave(@RequestBody JSONObject commandReview) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        JSONArray jsonArray = commandReview.getJSONArray("applyInfoList");
        List<CommandReview> commandReviewList = (List<CommandReview>) JSONArray.parseArray(jsonArray.toJSONString(),CommandReview.class);
        for (CommandReview cr : commandReviewList ) {
            commandReviewService.insertOrUpdate(cr);
            if ( "Y".equals( cr.getReviewStatus()) ) {
                EntityWrapper<CommandSend>  entityWrapper = new EntityWrapper();
                CommandSend commandSend = new CommandSend();
                commandSend.setHandle( cr.getzCommandSendBo());
                entityWrapper.setEntity( commandSend );
                commandSendService.selectOne( entityWrapper );
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(commandSend);
                producerService.sendMsgNoReponse("eq.holdRelease",jsonObject.toJSONString());
            }
        }
        int count = 0;
        try {
            //count = commandReviewService.insertOrUpdate(commandReview) ? 1 : 0;
        } catch (Exception e) {
            logger.error("commandReviewSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : commandReview);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult commandReviewDelete(@PathVariable("id") String id){
        int count;
        try {
            count = commandReviewService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("commandReviewDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = commandReviewService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("commandReviewBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }
}